package com.wry.myphotowall.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.wry.myphotowall.MyApplication;
import com.wry.myphotowall.R;
import com.wry.myphotowall.activity.PhotoPickerActivity;
import com.wry.myphotowall.adapter.PhotoWallAdapter;
import com.wry.myphotowall.divider_recylerview.DividerGridItemDecoration;
import com.wry.myphotowall.listener.OnItemClickListerner;
import com.wry.myphotowall.util.Common;
import com.wry.myphotowall.util.ImageCaptureManager;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class PhotoWallFragment extends Fragment implements View.OnClickListener {

    /**
     * 最大图片选择数量
     */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /**
     * 默认选择集
     */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_list";
    /**
     * 屏幕高度
     */
    public static final String EXTRA_SCREEN_HEIGHT = "screen_height";
    /**
     * 显示相机拍照
     */
    public static final String SHOWCAMERA = "showcamera";
    /**
     * 图片裁剪
     */
    public static final String SHOWCUT = "showcut";
    /**
     * 选择图片完成点击完成按钮
     */
    TextView tvComplete;
    /**
     * 选择各类图片文件夹按钮（relayout）
     */
    RelativeLayout layout_bottom_actionbar;
    /**
     * 预览已选择的图片按钮
     */
    TextView tvPreview;

    TextView mTopTv;

    /**
     * 当前文件夹下图片名列表
     */
    private List<String> mImgNames = new ArrayList<>();

    private int maxCount = 9;//最多选择的图片张数
    private String mDesireSearchPath;//默认选择的文件夹
    private boolean isShowCamera = true;//默认显示照相按钮
    private boolean isShowCut = true;//默认进行图片裁剪

    RecyclerView mRecyclerView;
    private PhotoWallAdapter mAdapter;

    private String[] perms = {Manifest.permission.CAMERA};


    private View rootView;

    public static PhotoWallFragment newInstance(int screenHeight, int selectCount, String searchPath, boolean isShowCamera, boolean isShowCut) {

        Bundle args = new Bundle();
        args.putInt(EXTRA_SCREEN_HEIGHT, screenHeight);
        args.putInt(EXTRA_SELECT_COUNT, selectCount);
        args.putString(EXTRA_DEFAULT_SELECTED_LIST, searchPath);
        args.putBoolean(SHOWCAMERA, isShowCamera);
        args.putBoolean(SHOWCUT, isShowCut);
        PhotoWallFragment fragment = new PhotoWallFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //选择图片数量
        maxCount = getArguments().getInt(EXTRA_SELECT_COUNT);
        //默认选择
        mDesireSearchPath = getArguments().getString(EXTRA_DEFAULT_SELECTED_LIST);
        isShowCamera = getArguments().getBoolean(SHOWCAMERA);
        isShowCut = getArguments().getBoolean(SHOWCUT);
//        captureManager = new ImageCaptureManager(getActivity());
//        //扫描图片
//        getImages();
    }

    private void initView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mTopTv = (TextView) getActivity().findViewById(R.id.tv_back);
        tvComplete = (TextView) getActivity().findViewById(R.id.tv_commit);
        layout_bottom_actionbar = (RelativeLayout) getActivity().findViewById(R.id.layout_bottom_actionbar);
        tvPreview = (TextView) getActivity().findViewById(R.id.tv_preview);

        tvPreview.setOnClickListener(this);

        mTopTv.setText("Images");
        mRecyclerView.setPadding(0, getActivity().getResources().getDimensionPixelSize(R.dimen.actionBarHeight) + Common.getStatusBarHeight(getActivity())
                , 0, getActivity().getResources().getDimensionPixelSize(R.dimen.actionBarHeight));
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        ImagePipeline imagePipeline = Fresco.getImagePipeline();
                        // 同时清除内存和磁盘缓存
                        imagePipeline.clearCaches();
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //保存fragment视图状态
        rootView = getPersistentView(inflater, container, savedInstanceState, R.layout.fragment_photo_wall);
        initView(rootView);
//        initEvent();
        return rootView;
    }

    /**
     * 保存fragment视图状态
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @param layoutId
     * @return
     */
    private View getPersistentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int layoutId) {

        if (rootView == null) {
            rootView = inflater.inflate(layoutId, container, false);
        } else {

            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_preview://预览选择的图片
                int[] screenLocation = new int[2];
                v.getLocationOnScreen(screenLocation);
                PhotoViewFragment fragment =
                        PhotoViewFragment.newInstance(PhotoWallAdapter.mSelectedImage, 0, maxCount, screenLocation,
                                v.getWidth(), v.getHeight());
                ((PhotoPickerActivity) getActivity()).addPhotoPagerFragment(fragment);
                break;
        }
    }


    /**
     * 绑定数据
     *
     * @param mImgDir
     */
    public void data2View(final File mImgDir) {
        /**
         * 文件夹路径个图片路径分开保存，减少了内存的消耗
         */
        //创建默认的线性LayoutManager
        GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
        mRecyclerView.setLayoutManager(mLayoutManager);
        DividerGridItemDecoration itemDecoration = new DividerGridItemDecoration(getActivity());
        mRecyclerView.addItemDecoration(itemDecoration);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mRecyclerView.setHasFixedSize(true);
        if(Common.empty(mImgDir)){//没有扫描出图片
            //创建并设置Adapter
            mAdapter = new PhotoWallAdapter(getActivity(), mImgNames, "", maxCount, isShowCamera);
            mRecyclerView.setAdapter(mAdapter);
        }else {
            mImgNames = Arrays.asList(mImgDir.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg"))
                        return true;
                    return false;
                }
            }));
            Collections.reverse(mImgNames);
            //创建并设置Adapter
            mAdapter = new PhotoWallAdapter(getActivity(), mImgNames, mImgDir.getAbsolutePath(), maxCount, isShowCamera);
            mRecyclerView.setAdapter(mAdapter);
        }
        //item选择回调
        mAdapter.setOnItemClickListerner(new OnItemClickListerner() {
            @Override
            public void onPhotoClick(View view, int position) {
                final int index = isShowCamera ? position - 1 : position;
                List<String> mImgUrls = new ArrayList<String>();
                for (int i = 0; i < mImgNames.size(); i++) {
                    mImgUrls.add(mImgDir + "/" + mImgNames.get(i));
                }
                int[] screenLocation = new int[2];
                view.getLocationOnScreen(screenLocation);
                PhotoViewFragment fragment =
                        PhotoViewFragment.newInstance(mImgUrls, index, maxCount, screenLocation,
                                view.getWidth(), view.getHeight());
                ((PhotoPickerActivity) getActivity()).addPhotoPagerFragment(fragment);
            }

            @Override
            public void onMarkClick(String path) {
                refreshUI(path);
            }

            @Override
            public void onCameraClick(View view) {
                ((PhotoPickerActivity) getActivity()).checkPermission(perms);
//                checkPermission(perms);
            }
        });
    }


    private void refreshUI(String path) {
        if (PhotoWallAdapter.mSelectedImage.contains(path)) {
            if (PhotoWallAdapter.mSelectedImage.size() != 0) {
                tvPreview.setEnabled(true);
                tvPreview.setText(getResources().getString(R.string.preview)
                        + "(" + PhotoWallAdapter.mSelectedImage.size() + ")");
                tvComplete.setEnabled(true);
                tvComplete.setText(String.format("%s(%d/%d)", getString(R.string.action_done)
                        , PhotoWallAdapter.mSelectedImage.size(), maxCount));
                tvComplete.setBackgroundResource(R.drawable.bg_complete_enable);
                tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x6), 0, getResources().getDimensionPixelSize(R.dimen.x6), 0);
            } else {
                tvPreview.setEnabled(false);
                tvPreview.setText(R.string.preview);
                tvComplete.setEnabled(false);
                tvComplete.setText(R.string.action_done);
                tvComplete.setBackgroundResource(R.drawable.bg_complete_unenable);
                tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x14), 0, getResources().getDimensionPixelSize(R.dimen.x14), 0);
            }
        } else {
            if (PhotoWallAdapter.mSelectedImage.size() == 0) {
                tvPreview.setEnabled(false);
                tvPreview.setText(R.string.preview);
                tvComplete.setEnabled(false);
                tvComplete.setText(R.string.action_done);
                tvComplete.setBackgroundResource(R.drawable.bg_complete_unenable);
                tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x14), 0, getResources().getDimensionPixelSize(R.dimen.x14), 0);
            } else {
                tvPreview.setEnabled(true);
                tvPreview.setText(getResources().getString(R.string.preview)
                        + "(" + PhotoWallAdapter.mSelectedImage.size() + ")");
                tvComplete.setEnabled(true);
                tvComplete.setText(String.format("%s(%d/%d)",
                        getString(R.string.action_done), PhotoWallAdapter.mSelectedImage.size(), maxCount));
                tvComplete.setBackgroundResource(R.drawable.bg_complete_enable);
                tvComplete.setPadding(getResources().getDimensionPixelSize(R.dimen.x6), 0, getResources().getDimensionPixelSize(R.dimen.x6), 0);
            }
        }
    }

    public void refreshData() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }
}
